package com.xu.service;

import com.alibaba.fastjson.JSON;
import com.xu.mapper.MovieDetailMapper;
import com.xu.pojo.MovieDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

@Component
public class MovieDetailService {
    @Autowired
    private MovieDetailMapper movieDetailMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public boolean insertMovieDetail(MovieDetail movieDetail){
        if (movieDetail.getType() == null)
            return false;

        return movieDetailMapper.insertMovieDetail(movieDetail) > 0 ? true:false;
    }

    public MovieDetail queryMovieDetail(Integer id) {
        List<Object> movieDetails = redisTemplate.opsForList().range("movieDetails", 0, -1);

        for (Object item : movieDetails) {
            MovieDetail movieDetail = JSON.parseObject((String) item,MovieDetail.class);
            if (movieDetail.getMovieId() == id){
                return movieDetail;
            }
        }
        MovieDetail movieDetail = movieDetailMapper.queryMovieDetail(id);
        redisTemplate.opsForList().rightPush("movieDetails",JSON.toJSONString(movieDetail));

        return movieDetail;
    }
}
